package org.lewis.demo.controller;

import io.mybatis.common.core.DataResponse;
import io.mybatis.common.core.RowsResponse;
import org.lewis.demo.model.TDemoBook;
import org.lewis.demo.service.TDemoBookService;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;

@RequestMapping("book")
@RestController
public class TDemoBookController {

    private final TDemoBookService bookService;

    public TDemoBookController(TDemoBookService bookService) {
        this.bookService = bookService;
    }

    @PostMapping
    public DataResponse<TDemoBook> save(@RequestBody TDemoBook book) {
        book.setId(UUID.randomUUID().toString());
        return DataResponse.ok(this.bookService.saveSelective(book));
    }

    @GetMapping
    public RowsResponse<TDemoBook> findList(@RequestBody TDemoBook book) {
        return RowsResponse.ok(this.bookService.findList(book));
    }

    @GetMapping(value = "{id}")
    public DataResponse<TDemoBook> findById(@PathVariable("id") String id) {
        return DataResponse.ok(this.bookService.findById(id));
    }

    @PutMapping(value = "{id}")
    public DataResponse<TDemoBook> update(@PathVariable("id") String id, @RequestBody TDemoBook book) {
        book.setId(id);
        return DataResponse.ok(this.bookService.updateSelective(book));
    }

    @DeleteMapping(value = "{id}")
    public DataResponse<Boolean> deleteById(@PathVariable("id") String id) {
        return DataResponse.ok(this.bookService.deleteById(id) == 1);
    }

    @GetMapping("page")
    public RowsResponse<TDemoBook> findByPage(@RequestBody Map<String, Object> param,
                                              @RequestParam Integer pageNum,
                                              @RequestParam Integer pageSize) {
        return this.bookService.findByPage(param, pageNum, pageSize);
    }

    @DeleteMapping
    public DataResponse<Integer> deleteAll() {
        return DataResponse.ok(this.bookService.delete(new TDemoBook()));
    }

}
